﻿using System;
using System.Web;
using System.Configuration;
using System.Security.Cryptography;
using System.Text;
using System.Web.Security;
using System.Net.Mail;
using System.Collections.Generic;

namespace TBM.Core
{
    public class App
    {
        /// <summary>
        /// 得到加密后的密码
        /// </summary>
        /// <param name="password">密码明文</param>
        /// <returns></returns>
        public static string GetPassword(string password)
        {
            if (password == null) return password;

            string newPwd = null;
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] bytes = Encoding.UTF8.GetBytes(password);
            byte[] encryp = (new SHA1Managed()).ComputeHash(bytes);
            newPwd = Convert.ToBase64String(encryp);
            bytes = Encoding.UTF8.GetBytes(newPwd);
            encryp = md5.ComputeHash(bytes);
            newPwd = BitConverter.ToString(encryp).Replace("-", "");

            return newPwd;
        }

        /// <summary>
        /// 检验当前用户密码
        /// </summary>
        /// <param name="password">密码明文</param>
        /// <returns></returns>
        public static bool CheckPassword(string password)
        {
            if (HttpRuntime.Cache.Get("User") != null)
            {
                return (HttpRuntime.Cache.Get("User") as Models.User).Password == GetPassword(password);
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 将字符串编码为Base64
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ToBase64(string str)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(str);

            return Convert.ToBase64String(bytes);
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="subject">标题</param>
        /// <param name="content">内容（默认HTML格式）</param>
        /// <param name="addresses">收件地址</param>
        /// <returns></returns>
        public static Models.ExecuteResult SendEmail(string subject, string content, List<MailAddress> addresses)
        {
            return SendEmail(subject, content, true, addresses);
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="subject">标题</param>
        /// <param name="content">内容（默认HTML格式）</param>
        /// <param name="addresses">收件地址</param>
        /// <returns></returns>
        public static Models.ExecuteResult SendEmail(string subject, string content, MailAddress addresses)
        {
            return SendEmail(subject, content, true, addresses);
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="subject">标题</param>
        /// <param name="content">内容</param>
        /// <param name="isBodyHTML">是否是HTML</param>
        /// <param name="addresses">收件地址</param>
        /// <returns></returns>
        public static Models.ExecuteResult SendEmail(string subject, string content, bool isBodyHTML, MailAddress addresses)
        {
            return SendEmail(subject, content, isBodyHTML, new List<MailAddress> { addresses });
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="subject">标题</param>
        /// <param name="content">内容</param>
        /// <param name="isBodyHTML">是否是HTML</param>
        /// <param name="addresses">收件地址</param>
        /// <returns></returns>
        public static Models.ExecuteResult SendEmail(string subject, string content, bool isBodyHTML, List<MailAddress> addresses)
        {
            // 发送邮件没有提供接受地址
            if (addresses == null)
            {
                return new Models.ExecuteResult
                {
                    Result = false,
                    Code = Lang.SEND_MAIL_NO_ADDRESS.Code,
                    Message = Lang.SEND_MAIL_NO_ADDRESS.Message
                };
            }

            MailMessage mail = new MailMessage();
            SmtpClient smtp = new SmtpClient();

            smtp.Host = Config.SMTPAddress;
            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
            smtp.Credentials = new System.Net.NetworkCredential(Config.SMTPUserName, Config.SMTPPassword);

            mail.From = new MailAddress(Config.SMTPEmailAddress, Config.SMTPDisplayName);
            mail.Subject = subject;
            mail.IsBodyHtml = isBodyHTML;
            mail.Body = content;

            foreach (MailAddress address in addresses)
            {
                mail.To.Add(address);
            }

            LangItem lang = new LangItem();
            try
            {
                smtp.Send(mail);
                lang = Lang.SEND_MAIL_SUCCESS;
            }
            catch
            {
                lang = Lang.SEND_MAIL_FAILED;
            }
            finally
            {
                smtp.Dispose();
                mail.Dispose();
            }

            return new Models.ExecuteResult
            {
                Result = lang.Code == Lang.SEND_MAIL_SUCCESS.Code,
                Code = lang.Code,
                Message = lang.Message
            };
        }
    }
}